package osb.map.main;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import com.ljp.ani.R;
import osb.map.main.HuaQiang_LazyScrollView.OnScrollListener;
import osb.map.publicdata.Public_Operate_And_Data;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

/**
 * 画墙activity
 * @author Administrator
 *
 */

public class HuaQiang_Main extends Activity {

	
	static public HuaQiang_Main huaQiang_main;
	private HuaQiang_LazyScrollView waterfall_scroll;
	private LinearLayout waterfall_container;
	private ArrayList<LinearLayout> waterfall_items;
	private Display display;
	private AssetManager asset_manager;
	private List<String> image_filenames;
	private final String image_path = "images";
	private Handler handler;
	private int item_width;

	private int column_count = 4;// 显示列数
	private int page_count = 30;// 每次加载30张图片

	private int current_page = 0;// 当前页数

	private int[] topIndex;
	private int[] bottomIndex;
	private int[] lineIndex;
	private int[] column_height;// 每列的高度

	private HashMap<Integer, String> pins;

	private int loaded_count = 0;// 已加载数量

	private HashMap<Integer, Integer>[] pin_mark = null;

	private Context context;
	boolean IsShowMenu = false; // 是否全屏
	private HashMap<Integer, HuaQiang_FlowView> iviews;
	private int range;
	int scroll_height;
 
	private ImageView imageView;
	private  PopupWindow popupWindow;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.huaqiang_main);
		huaQiang_main=this;
		
		display = this.getWindowManager().getDefaultDisplay();
		item_width = display.getWidth() / column_count;// 根据屏幕大小计算每列大小
		asset_manager = this.getAssets();

		column_height = new int[column_count];
		context = this;
		iviews = new HashMap<Integer, HuaQiang_FlowView>();
		pins = new HashMap<Integer, String>();
		pin_mark = new HashMap[column_count];

		this.lineIndex = new int[column_count];
		this.bottomIndex = new int[column_count];
		this.topIndex = new int[column_count];

		for (int i = 0; i < column_count; i++) {
			lineIndex[i] = -1;
			bottomIndex[i] = -1;
			pin_mark[i] = new HashMap();
		}

		InitLayout();
		
		Button button=(Button)findViewById(R.id.huaqiang_back);
		 //点击返回
		button.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)   
			{
				HuaQiang_Main.this.finish();
			}
		});
		Button huaqiang_send_photo=(Button)findViewById(R.id.huaqiang_send_photo);
		 //添加图片
		huaqiang_send_photo.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)   
			{
				Toast.makeText(HuaQiang_Main.this, "未开放", Toast.LENGTH_SHORT).show();
			}
		});

	}

	private void InitLayout() {
		waterfall_scroll = (HuaQiang_LazyScrollView) findViewById(R.id.waterfall_scroll);
		range = waterfall_scroll.computeVerticalScrollRange();//

		waterfall_scroll.getView();
		waterfall_scroll.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onTop() {
				// 滚动到最顶端
				Log.d("LazyScroll", "Scroll to top");
			}

			@Override
			public void onScroll() {

			}

			@Override
			public void onBottom() {
				// 滚动到最低端
				AddItemToContainer(++current_page, page_count);
			}

			@Override
			public void onAutoScroll(int l, int t, int oldl, int oldt) {
				scroll_height = waterfall_scroll.getMeasuredHeight();
				Log.d("MainActivity", "scroll_height:" + scroll_height);
				if (t > oldt) {// 向下滚动
					if (t > 2 * scroll_height) {// 超过两屏幕后

						for (int k = 0; k < column_count; k++) {

							LinearLayout localLinearLayout = waterfall_items
									.get(k);

							if (pin_mark[k].get(Math.min(bottomIndex[k] + 1,
									lineIndex[k])) <= t + 3 * scroll_height) {// 最底部的图片位置小于当前t+3*屏幕高度

								((HuaQiang_FlowView) waterfall_items.get(k)
										.getChildAt(
												Math.min(1 + bottomIndex[k],
														lineIndex[k])))
										.Reload();

								bottomIndex[k] = Math.min(1 + bottomIndex[k],
										lineIndex[k]);

							}
							Log.d("MainActivity",
									"headIndex:" + topIndex[k]
											+ "  footIndex:" + bottomIndex[k]
											+ "  headHeight:"
											+ pin_mark[k].get(topIndex[k]));
							if (pin_mark[k].get(topIndex[k]) < t - 2
									* scroll_height) {// 未回收图片的最高位置<t-两倍屏幕高度

								int i1 = topIndex[k];
								topIndex[k]++;
								
								//向上滚动回收。和
								((HuaQiang_FlowView) localLinearLayout.getChildAt(i1)).recycle();
								Log.d("MainActivity", "recycle,k:" + k + " headindex:" + topIndex[k]);

							}
						}
					}
				} else {

					for (int k = 0; k < column_count; k++) {
						LinearLayout localLinearLayout = waterfall_items.get(k);
						if (pin_mark[k].get(bottomIndex[k]) > t + 3
								* scroll_height) {
							((HuaQiang_FlowView) localLinearLayout.getChildAt(bottomIndex[k])).recycle();
							((HuaQiang_FlowView) localLinearLayout.getChildAt(bottomIndex[k])).recycle();
							bottomIndex[k]--;
						}

						if (pin_mark[k].get(Math.max(topIndex[k] - 1, 0)) >= t
								- 2 * scroll_height) {
							((HuaQiang_FlowView) localLinearLayout.getChildAt(Math.max(
									-1 + topIndex[k], 0))).Reload();
							topIndex[k] = Math.max(topIndex[k] - 1, 0);
						}
					}

				}

			}
		});

		waterfall_container = (LinearLayout) this
				.findViewById(R.id.waterfall_container);
		handler = new Handler() {

			@Override
			public void dispatchMessage(Message msg) {

				super.dispatchMessage(msg);
			}
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:

					HuaQiang_FlowView v = (HuaQiang_FlowView) msg.obj;
					int w = msg.arg1;
					int h = msg.arg2;
					String f = v.getFlowTag().getFileName();
					int columnIndex = GetMinValue(column_height);

					v.setColumnIndex(columnIndex);

					column_height[columnIndex] += h;

					pins.put(v.getId(), f);
					iviews.put(v.getId(), v);
					waterfall_items.get(columnIndex).addView(v);

					lineIndex[columnIndex]++;

					pin_mark[columnIndex].put(lineIndex[columnIndex],
							column_height[columnIndex]);
					bottomIndex[columnIndex] = lineIndex[columnIndex];
					break;
				}

			}

			@Override
			public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
				return super.sendMessageAtTime(msg, uptimeMillis);
			}
		};

		waterfall_items = new ArrayList<LinearLayout>();

		for (int i = 0; i < column_count; i++) {
			LinearLayout itemLayout = new LinearLayout(this);
			LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams(
					item_width, LayoutParams.WRAP_CONTENT);

			itemLayout.setPadding(2, 2, 2, 2);
			itemLayout.setOrientation(LinearLayout.VERTICAL);

			itemLayout.setLayoutParams(itemParam);
			waterfall_items.add(itemLayout);
			waterfall_container.addView(itemLayout);
		}

		// 加载所有图片路径

		try {
			image_filenames = Arrays.asList(asset_manager.list(image_path));

		} catch (IOException e) {
			e.printStackTrace();
		}
		// 第一次加载
		AddItemToContainer(current_page, page_count);
	}

	private void AddItemToContainer(int pageindex, int pagecount) {
		int currentIndex = pageindex * pagecount;

		int imagecount = 10000;// image_filenames.size();
		for (int i = currentIndex; i < pagecount * (pageindex + 1)
				&& i < imagecount; i++) {
			loaded_count++;
			Random rand = new Random();
			int r = rand.nextInt(image_filenames.size());
			AddImage(image_filenames.get(r),
					(int) Math.ceil(loaded_count / (double) column_count),
					loaded_count);
		}

	}

	private void AddImage(String filename, int rowIndex, int id) {

		HuaQiang_FlowView item = new HuaQiang_FlowView(context);
		item.setRowIndex(rowIndex);
		item.setId(id);
		item.setViewHandler(this.handler);
		// 多线程参数
		HuaQiang_FlowTag param = new HuaQiang_FlowTag();
		param.setFlowId(id);
		param.setAssetManager(asset_manager);
		param.setFileName(image_path + "/" + filename);
		param.setItemWidth(item_width);

		item.setFlowTag(param);
		item.LoadImage();

	}

	private int GetMinValue(int[] array) {
		int m = 0;
		int length = array.length;
		for (int i = 0; i < length; ++i) {

			if (array[i] < array[m]) {
				m = i;
			}
		}
		return m;
	}
	
	  // 点击显示大图 popup 
	  void openPopupwin(String path) {
		LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(
				R.layout.huaqiang_show_single, null, true);
		imageView=(ImageView)menuView.findViewById(R.id.show_single_photho);
		
		Bitmap bgimg0 = getImageFromAssetsFile(path);
		
		imageView.setImageBitmap(bgimg0);
		
		LinearLayout LinearLayout=(LinearLayout)menuView.findViewById(R.id.show_single_photho_layout);
		LinearLayout.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				 popupWindow.dismiss();
				  popupWindow = null;
			}
		});
		popupWindow = new PopupWindow(menuView, LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT, true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setOutsideTouchable(true); 
		popupWindow.showAtLocation(findViewById(R.id.huaqiang_parents), Gravity.CENTER | Gravity.CENTER, 0, 0);  
		popupWindow.update();
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (popupWindow != null && imageView.isShown()) {
			popupWindow.dismiss();
			popupWindow = null;
		}
		return super.onTouchEvent(event);

	}

	    
	    /**
	     * 从Assets中读取图片
	     */
	     private Bitmap getImageFromAssetsFile(String fileName)
	     {
	     Bitmap image = null;
	     AssetManager am = getResources().getAssets();
	     try
	     {
	     InputStream is = am.open(fileName);
	     image = BitmapFactory.decodeStream(is);
	     is.close();
	     }
	     catch (IOException e)
	     {
	     e.printStackTrace();
	     }
	     
	    return image;
	     
	    }
	  
	    // 点击MENU 事件 执行全屏视图
		@Override
	    public boolean onPrepareOptionsMenu(Menu menu)
		{
			int v = this.getWindow().getAttributes().flags;
//			if (v != 66816)
//			{ 
//				this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
//			} else
//			{
//				this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//			}
//			
			// 全屏
			if (Public_Operate_And_Data.IsHuaQiangFullScreen)
			{
				Public_Operate_And_Data.IsHuaQiangFullScreen = false;
				this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			}
			else {
				Public_Operate_And_Data.IsHuaQiangFullScreen = true;
				this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
			}
			
			
			return true;
		}
		
	    /**
		 * menu
		 */
//		@Override
//		public boolean onCreateOptionsMenu(Menu menu) {
//			menu.add(Menu.NONE, Menu.FIRST + 1, 3, "分享下载").setIcon(android.R.drawable.ic_menu_send);
//			return true;
//
//		}
//
//		@Override
//		public boolean onOptionsItemSelected(MenuItem item) {
//			switch (item.getItemId()) {
//			case Menu.FIRST + 1:
//				Intent intent = new Intent();
//				intent.setClass(HuaQiang_Main.this, ShareActivity.class);
//				HuaQiang_Main.this.startActivity(intent);
//
//				break;
//			}
//			return false;
//		}
}
